#!/bin/bash

# $1=IDE_ROOT, IDE根目录路径
# $2=BUILD_CONFIG, 待构建配置
# $3=PRJ_PATH, 待构建项目路径

IDE_ROOT=$1
BUILD_CONFIG=$2
PRJ_PATH=$3
IS_LINUX="true"

OLD_IFS="$IFS"

if [ ! -d "$IDE_ROOT" ]; then
    echo "Aruments error. IDE_ROOT $IDE_ROOT do not exist"
    exit 1
fi

if [ -z "$BUILD_CONFIG" ]; then
    echo "Aruments error. BUILD_CONFIG not supply"
    exit 1
fi

if [ -z "$PRJ_PATH" ]; then
    echo "Aruments error. PRJ_PATH not supply"
    exit 1
fi

if [ ! -f "$PRJ_PATH/buildTmp.txt" ]; then
    echo "未找到构建配置文件，构建失败！！"
    exit 1
fi

if [ -f "$IDE_ROOT/host/cygwin/bin/tr.exe" ]; then
    IS_LINUX="false"
fi

export PATH="$IDE_ROOT/host/pub/jre/bin:$PATH"
if [ "$IS_LINUX" == "false" ]; then
    export PATH="$IDE_ROOT/host/cygwin/bin:$PATH"
fi
TPATH="$PATH"

# 检查指定路径的 JAR 文件是否存在
if [ -f "$IDE_ROOT/host/java/avic.actri.hAndcmakeFileBuilder.jar" ]; then
	# 执行Jar, 为cmake生成前置依赖文件
	echo "java -jar $IDE_ROOT/host/java/avic.actri.hAndcmakeFileBuilder.jar $PRJ_PATH $BUILD_CONFIG $IDE_ROOT"
	$IDE_ROOT/host/pub/jre/bin/java -jar $IDE_ROOT/host/java/avic.actri.hAndcmakeFileBuilder.jar $PRJ_PATH $BUILD_CONFIG $IDE_ROOT
	if [ $? -ne 0 ]; then
    	echo "Build failed. avic.actri.hAndcmakeFileBuilder.jar return with error"
    	exit 1
	fi
fi

function doBuild() {
    cmake_cmd=$1
    build_cmd=$2
    
    # 2 执行cmake指令
    Modified_Cmake_Cmd=$(echo $cmake_cmd | $IDE_ROOT/host/cygwin/bin/sed 's/;/"/g')
    echo "****** Cmake_Cmd = $Modified_Cmake_Cmd"
    eval $Modified_Cmake_Cmd
    if [ $? -ne 0 ]; then
        echo "Build failed. cmake cmd return with error"
        exit 1
    fi
    # 3 执行build
    echo "****** build_cmd = $build_cmd"
    eval $build_cmd
    if [ $? -ne 0 ]; then
        echo "Build failed. build cmd return with error"
        exit 1
    fi
}

lineno=0
while IFS= read -r line
do
    IFS='#'
    read -r env_path cmake_cmd build_cmd <<< "$line"
    if [ "$env_path" != "-" ]; then
        export PATH="$env_path:$TPATH"
        echo "***** PATH = $PATH"
    fi
    doBuild "$cmake_cmd" "$build_cmd"
    ((lineno++))
done < "$PRJ_PATH/buildTmp.txt"

$IDE_ROOT/host/cygwin/bin/rm $PRJ_PATH/buildTmp.txt

IFS="$OLD_IFS"
